package com.example.demo.service.impl;

import com.example.demo.common.response.ResponsePage;
import com.example.demo.entity.*;
import com.example.demo.entity.Dto.AbnormalInfo;
import com.example.demo.entity.Dto.HealthExaminationRecordDto;
import com.example.demo.entity.Dto.TotalInfo;
import com.example.demo.entity.Dto.VaccinationDto;
import com.example.demo.entity.VO.PetHealthInfo;
import com.example.demo.entity.VO.PetInfoDetail;
import com.example.demo.entity.VO.VaccinationRecord;
import com.example.demo.entity.VO.VaccinationVO;
import com.example.demo.entity.param.ExaminationRecordParam;
import com.example.demo.entity.param.PetParam;
import com.example.demo.entity.param.PetRecordInfoParam;
import com.example.demo.exception.Asserts;
import com.example.demo.mapper.PetInfoMapper;
import com.example.demo.mapper.PetMapper;
import com.example.demo.service.PetInfoService;
import com.example.demo.service.RedisService;
import com.example.demo.util.AsyncUtil;
import com.example.demo.util.MemberUtil;
import com.example.demo.util.YunOxTools;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

@Service
public class PetInfoServiceImpl implements PetInfoService {

    @Resource
    private PetInfoMapper petHeathInfoMapper;
    @Resource
    private PetMapper petMapper;
    @Resource
    private RedisService redisService;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public ResponsePage<PetHealthInfo> getPetHeathInfo(PetParam petParam) {
        PageHelper.startPage(petParam.getPageNum(), petParam.getPageSize());
        List<PetHealthInfo> petHealthInfoList = petHeathInfoMapper.getPetHeathInfo(petParam);
        return ResponsePage.restPage(new PageInfo<>(petHealthInfoList));
    }

    @Override
    public void addPet(Pet pet) {
        if (YunOxTools.isEmpty(pet)) {
            Asserts.fail("新增内容为空，检查参数");
        }
        pet.setUserId(Math.toIntExact(MemberUtil.getUserId()));
        petHeathInfoMapper.addPet(pet);
    }

    @Override
    public void editPet(Pet pet) {
        if (YunOxTools.isEmpty(pet) || pet.getPetId() == null) {
            Asserts.fail("参数不符，请检查");
        }
        petHeathInfoMapper.editPet(pet);
    }

    @Override
    public ResponsePage<Pet> getPet(PetParam petParam) {
        if (petParam.getPageNum() == null || petParam.getPageSize() == null || petParam.getPageNum() < 1 || petParam.getPageSize() < 1) {
            Asserts.fail("分页参数有误");
        }
        PageHelper.startPage(petParam.getPageNum(), petParam.getPageSize());
        List<Pet> petList = petHeathInfoMapper.getPet(petParam);
        return ResponsePage.restPage(new PageInfo<>(petList));
    }

    @Override
    public List<PetInfoDetail> getPetInfo() {
        Long userId = MemberUtil.getUserId();
//        List<PetInfoDetail> petInfoCache = (List<PetInfoDetail>) redisService.getWithTimeout("petInfo_" + userId);
//        if (petInfoCache != null) {
//            return petInfoCache;
//        }
        List<PetInfoDetail> petInfo = petMapper.getPetInfo(MemberUtil.getUserId());
//        redisService.set("petInfo_" + userId, petInfo);
        return petInfo;
    }

    @Override
    public List<VaccinationVO> getAllVaccination() {
        return petMapper.getAllVaccination();
    }

    @Override
    public List<VaccinationDto> getVaccinationRecord() {
        return petMapper.getVaccinationRecord(MemberUtil.getUserId());
    }

    @Override
    public void addVaccinationRecord(VaccinationRecord vaccinationRecord) {
        vaccinationRecord.setUserId(Math.toIntExact(MemberUtil.getUserId()));
        VaccinationRecord record =  petMapper.getVaccinationRecordInfo(vaccinationRecord);
        if (!YunOxTools.isEmpty(record)){
            Asserts.fail("该宠物已接种过疫苗，请勿重复添加");
        }
        if (YunOxTools.isEmpty(vaccinationRecord)) {
            Asserts.fail("添加记录为空，检查参数");
        }
        Pet pet = petMapper.getPetInfoByPetId(vaccinationRecord.getPetId());
        if (!pet.getVaccinationRecond().equals("已接种")) {
            pet.setVaccinationRecond("已接种");
            petMapper.updatePetInfo(pet);
        }
        petMapper.addVaccinationRecord(vaccinationRecord);
    }

    /*
    在宠物管理系统中，Redis 的应用主要体现在用户信息缓存、宠物健康状态缓存和 Token 缓存三个方面。
    用户信息缓存：系统将用户的基本信息（如用户名、角色、权限等）存储在 Redis 中。当需要获取用户信息时，系统优先从 Redis 缓存读取。如果缓存中存在数据，则直接返回，减少数据库访问；如果不存在，则从 MySQL 数据库查询并更新缓存，从而提高响应速度和系统性能。
    宠物健康状态缓存：宠物的健康状态信息（如体检结果、疫苗接种状态等）也被存储在 Redis 中。用户查询时，系统优先从缓存读取。若缓存中无数据，则从数据库查询并存入缓存，提升查询效率，减轻数据库压力，优化用户体验。
    Token缓存：将用户登录时生成的Token存储在Redis缓存中，设置有效期限用于实现用户认证和会话管理[12]。当用户发起请求时，系统校验Token是否存在于Redis缓存中且未过期，若有效则允许操作，否则要求用户重新登录。
    通过缓存机制，系统能够显著提升数据访问效率，减轻数据库压力，提高用户体验。

    用户信息缓存和token这两个，因为你user表结构很简单，而且不需要去做多表查询，所以直接从token里解析就好了token里面已经包含了userInfo的内容
    用户信息缓存，是因为有的系统中，需要返回的用户信息不单单有名字这些，需要返回部门啊，组织，角色这些信息，所以需要数据库消耗资源，你的宠物系统没这些，所有用不到
    宠物健康状态缓存这个，健康状态你查的频率其实不多，所以直接redis里放那个totalInfo，更省事一点，因为totalInfo包含了健康信息
     */
    @Override
    public List<PetHealthExaminationRecord> getHealthCheckUpRecords(ExaminationRecordParam param) {
        return petMapper.getHealthCheckUpRecords(param);
    }

    @Override
    public List<PetActivities> getPetActivityList() {
        return petMapper.getPetActivityList(MemberUtil.getUserId());
    }

    @Override
    public List<PetDrink> getPetDrinkInfo() {
        return petMapper.getPetDrinkInfo(MemberUtil.getUserId());
    }

    @Override
    public List<AnomalyRecord> getAnomalyRecord(String anomaly) {
        Long userId = MemberUtil.getUserId();
        return petMapper.getAnomalyRecord(anomaly, userId);
    }

    @Override
    public TotalInfo getTotalInfoById(Integer id) {
//        TotalInfo TotalInfoByIdCache = (TotalInfo) redisService.getWithTimeout("totalInfo_" + id);
//        if (TotalInfoByIdCache != null) {
//            return TotalInfoByIdCache;
//        }
        TotalInfo totalInfo = new TotalInfo();
        totalInfo.setId(id);
        totalInfo.setPetImgs(petMapper.getImgs(id));
        totalInfo.setPetDrinkList(petMapper.getPetDrinkList(id));
        totalInfo.setAnomalyRecordList(petMapper.getAnomalyRecordList(id));
        System.out.println(totalInfo.getAnomalyRecordList());
        totalInfo.setPetsActivitiesList(petMapper.getPetActivityList2(id));
        totalInfo.setVaccinationRecordList(petMapper.getVaccinationRecordList(id));
        totalInfo.setExaminationRecordList(petMapper.getExaminationRecordList(id));
        totalInfo.setDailyData(petMapper.getDailyData(id));
//        redisService.set("totalInfo_" + id, totalInfo);
        return totalInfo;
    }

    @Override
    public List<PetInfoDetail> editPetInfo() {
        return null;
    }


    @Override
    public void editPetInfo(Pet pet) {
        petMapper.updatePetInfo(pet);
    }

    @Override
    public void addPetDailyInfo(PetDailyData data) {
        if (YunOxTools.isEmpty(data)) {
            Asserts.fail("添加记录为空，检查参数");
        }
        petMapper.addPetDailyInfo(data);
    }



    public static void sendPost(String urlStr, String jsonPayload, String token) {
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 设置请求方式
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Authorization", "Bearer " + token);

            // 发送请求数据
            if (jsonPayload != null && !jsonPayload.isEmpty()) {
                try (OutputStream os = conn.getOutputStream()) {
                    os.write(jsonPayload.getBytes("UTF-8"));
                }
            }

            // 获取响应
            String responseMessage = conn.getContent().toString();
            System.out.println("Response Message: " + responseMessage);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String url = "http://localhost:8090/pet/getPetInfo";
        String token = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ6aGFuZ3NoYW4iLCJpZCI6MSwidXNlcm5hbWUiOiJ6aGFuZ3NoYW4iLCJmdWxsTmFtZSI6IuW8oOS4iSIsInBhc3N3b3JkIjoiSDAzR3JUL2kyVzNRVFJwaVBPMTBWdz09IiwicGhvbmUiOiIxOTkxMjM0MTIzNCIsImdlbmRlciI6MCwiYWdlIjoxOCwiYWRkcmVzcyI6IuS4iua1t-W4giIsImF2YXRhciI6Imh0dHBzOi8vd3d3Lnl1bm94LmNuL2ltYWdlL-W8oOS4iS5wbmciLCJpYXQiOjE3NDIxNDc4MjcsImV4cCI6MTc0Mjg2NzgyN30.S0jkIAO84sq7mr_8dzVA1bGGItHDNPYQcK_kbUDL5i85_DEy9iKefjqxvFVtMzUdLxeyDNkwfWIVyEG9xcGR0Q";
        for (int i = 0; i < 10000; i++) {
            int finalI = i;
            AsyncUtil.executeAsync(() -> {
                // 发送请求
                System.out.println("第" + finalI + "次请求");;
                sendPost(url, null, token);
            });
        }

    }
    @Override
    public void updateVaccinationRecord(VaccinationRecord vaccinationRecord) {
        petMapper.updateVaccinationRecord(vaccinationRecord);
    }

    @Override
    public AbnormalInfo checkPetAbnormalInfo() {
        return petMapper.checkPetAbnormalInfo(Math.toIntExact(MemberUtil.getUserId()));
    }

    @Override
    public void updatePetAbormal(AnomalyRecord record) {
        petMapper.updatePetAbormaly(record);
    }

    @Override
    public List<Doctor> getDocList() {
        return petMapper.getDocList();
    }

    @Override
    public void editDocInfo(Doctor doc) {
        if (YunOxTools.isEmpty(doc)) {
            Asserts.fail("医生信息为空，检查参数");
        }
        petMapper.editDocInfo(doc);
    }

    @Override
    public void addDoctor(Doctor doc) {
        petMapper.addDoctor(doc);
    }

    @Override
    public void addPhysicalRecord(PetRecordInfoParam param) {
        if (YunOxTools.isEmpty(param)) {
            Asserts.fail("记录信息为空，检查参数");
        }
//        param.setUserId(Math.toIntExact(MemberUtil.getUserId()));
//        Pet pet = new Pet();
//        pet.setUserId(param.getUserId());
//        pet.setPetName(param.getPetName());
//        pet.setGender(param.getPetGender());
//        pet.setAge(param.getPetAge());
//        pet.setWeight(param.getPetWeight());
//        pet.setSpecis(param.getPetSpecis());
//        pet.setDateOfBirth(param.getPetDateOfBirth());
//        pet.setSize(param.getPetSize());
//        pet.setHairLength(param.getPetHairLength());
//        pet.setColor(param.getPetColor());
//        pet.setMedicalHistory(param.getPetMedicalHistory());
//        pet.setAllergyHistory(param.getPetAllergyHistory());
//        pet.setDietaryHabits(param.getPetDietaryHabits());
//        pet.setActivityPreferences(param.getPetActivityPreferences());
//        pet.setSleepHabits(param.getPetSleepHabits());
//        pet.setSportHabits(param.getPetSportHabits());
//        petMapper.addPet(pet);
//        Long petId = pet.getPetId();
//        PetHealthExaminationRecord petHealthExaminationRecord = new PetHealthExaminationRecord();
//        petHealthExaminationRecord.setPetId(petId);
//        petHealthExaminationRecord.setHeight(param.getExaHeight());
//        petHealthExaminationRecord.setWeight(param.getExaWeight());
//        petHealthExaminationRecord.setHeartRate(param.getExaHeartRate());
//        petHealthExaminationRecord.setRespiratoryRate(param.getExaRespiratoryRate());
//        petHealthExaminationRecord.setTemperature(param.getExaTemperature());
//        petHealthExaminationRecord.setBloodPressure(param.getExaBloodPressure());
//        petHealthExaminationRecord.setBloodtestResults(param.getExaBloodtestResults());
//        petHealthExaminationRecord.setUrinetestResults(param.getExaUrinetestResults());
//        petHealthExaminationRecord.setXRayResults(param.getExaXRayResults());
//        petHealthExaminationRecord.setUltrasoundResults(param.getExaUltrasoundResults());
//        petHealthExaminationRecord.setDiagResult(param.getExaDiagResult());
//        petHealthExaminationRecord.setTreatmentPlan(param.getExaTreatmentPlan());
//        petHealthExaminationRecord.setNotes(param.getExaNotes());
//        petHealthExaminationRecord.setHealthResult(param.getExaHealthResult());
//        petMapper.addHealthExaminationRecord(petHealthExaminationRecord);
//        PetImgs petImgs = new PetImgs();
//        petImgs.setPetId(Math.toIntExact(petId));
//        petImgs.setCoverImg("http://localhost:8090/image/default2.png");
//        petImgs.setMainImg("http://localhost:8090/image/default1.png");
//        petImgs.setImgs("http://localhost:8090/image/default3.png;http://localhost:8090/image/default4.png;http://localhost:8090/image/default5.png");

    }

    @Override
    public void editPetImg(PetImgs img) {
        petMapper.editPetImg(img);
    }

    @Override
    public void addPetHealthExaminationRecord(PetHealthExaminationRecord record) {
        petMapper.addPetHealthExaminationRecord(record);
    }

    @Override
    public List<HealthExaminationRecordDto> getPetHealthExaminationRecordList(Integer petId) {
        return petMapper.getPetHealthExaminationRecordList(petId);
    }

    @Override
    public List<HealthExaminationRecordDto> searchHealthExaminationRecordList(HealthExaminationRecordDto param) {
        return petMapper.searchHealthExaminationRecordList(param);
    }

    @Override
    public List<PetInfoDetail> getPetInfo2(PetInfoDetail pet) {
        return petMapper.getPetInfo2(pet);
    }



    @Override
    public void addPetAbormal(AnomalyRecord record) {
        record.setUserId(Math.toIntExact(MemberUtil.getUserId()));
        petMapper.addPetAbormal(record);
    }

    @Override
    public void addPetDrink(PetDrink petDrink) {
        petMapper.addPetDrink(petDrink);
        System.out.println("保存宠物饮水信息：" + petDrink);
    }

    @Override
    public Integer petDataStatistic() {
        // 获取当前操作的用户的id
        Long userId = MemberUtil.getUserId();
        Integer recordNum =  petMapper.getPetHealthRecord(userId);
        return recordNum;
    }

    @Override
    public void addPetActivity(PetActivities petActivities) {
        // TODO：校验petActivities的时间
        petMapper.addPetActivity(petActivities);
    }

    @Override
    public void cleanPetActivity(Integer petId) {
        petMapper.cleanPetActivity( petId);
    }

}
